/*
 *
 *
Copyright (c) 1998-2001 Aristar, Inc. All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

3. The end-user documentation included with the redistribution, if any,
must include the following acknowledgment:

"This product includes software developed by Aristar, Inc. (http://www.aristar.com/)."

Alternately, this acknowledgment may appear in the software itself, if and
wherever such third-party acknowledgments normally appear.

4. The names "Dialect" and "Aristar, Inc." must not be used to endorse or
promote products derived from this software without prior written permission.
For written permission, please contact info@aristar.com.

5. Products derived from this software may not be called "Dialect", nor may
"Dialect" appear in their name, without prior written permission of Aristar, Inc.

THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
ARISTAR, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

This software consists of voluntary contributions made by many individuals
on behalf of Aristar, Inc.  For more information on Aristar, Inc.,
please see <http://www.aristar.com/>.

Portions of this software are based upon software freely available and
written by individuals not associated with Aristar, Inc.  Copyrights are
maintained in the relevant source code files.
 *
 *
 */

#include "stdafx.h"
#include "DConfigGlobals.h"
#include "ADOclasses.h"
#include <objbase.h>

#ifdef ADO_SUPPORT
//////////////////////////////////////

#ifdef UNDER_CE
#	define ADO_START 	bool bResult = false;
#	define ADO_END		return bResult;
#else
	static CString errFormatString = _T("ADO function or property failed: ");
#	define ADO_START 	bool bResult = false; try {
#	define ADO_END			\
			bResult = true; \
		}					\
		catch (_com_error e) { \
			m_LastError = errFormatString + e.ErrorMessage(); \
		} \
		return bResult;
#endif

//////////////////////////////////////////////////////////////

long TComObject::m_RefCount = 0;

TComObject::TComObject()
{
	if (m_RefCount == 0) {
		OutputDebugString(_T("**** Calling CoInitialize for ADO ****\n"));
#ifdef __WINCE__
		HRESULT h = CoInitializeEx(NULL, COINIT_MULTITHREADED);
#else
		HRESULT h = CoInitialize(NULL);
#endif
		if ((h != S_OK) && (h != S_FALSE)) {
			AfxMessageBox("CoInitialize failed", MB_OK);
		}
	}
	InterlockedIncrement(&m_RefCount);
}

TComObject::~TComObject()
{
	InterlockedDecrement(&m_RefCount);
	if (m_RefCount == 0) {
		OutputDebugString(_T("**** Calling CoUnitialize for ADO ****\n"));
		CoUninitialize();
	}
}

TComObject::TComObject(const TComObject& copy)
{
	if (this != &copy) {
		ASSERT(m_RefCount > 0); // If we are copying, there must be another
		InterlockedIncrement(&m_RefCount);
	}
}

TComObject& TComObject::operator = (const TComObject& copy)
{
	if (this != &copy) {
		ASSERT(m_RefCount > 0); // If we are copying, there must be another
		InterlockedIncrement(&m_RefCount);
	}
	return *this;
}

CString TComObject::GetLastError()
{
	return m_LastError;
}

/////////////////////////////////////////////////////////

bool TADOProperty::GetName(CString* name)
{
	ADO_START;
	*name = (LPCTSTR)m_pProperty->GetName();
	ADO_END;
}

bool TADOProperty::GetType(DataTypeEnum* type)
{
	ADO_START;
	*type = m_pProperty->GetType();
	ADO_END;
}

bool TADOProperty::GetValue(VARIANT* value)
{
	ADO_START;
	*value = m_pProperty->GetValue();
	ADO_END;
}

bool TADOProperty::SetValue(VARIANT value)
{
	ADO_START;
	HRESULT h = m_pProperty->put_Value(value);
	if (FAILED(h)) {
		bResult = false;
		m_LastError = _T("Failed to set property value");
	}
	ADO_END;
}

/////////////////////////////////////////////////////////

#ifdef UNDER_CE
TADOProperties::TADOProperties(){}
TADOProperties::~TADOProperties(){}
#endif

bool TADOProperties::GetCount(long* count)
{
	ADO_START;
	*count = m_pProperties->GetCount();
	ADO_END;
}

bool TADOProperties::GetItem(long index, TADOProperty* p)
{
	ADO_START;
	p->m_pProperty = m_pProperties->GetItem(index);
	ADO_END;
}

bool TADOProperties::GetItem(LPCTSTR name, TADOProperty* p)
{
	ADO_START;
	p->m_pProperty = m_pProperties->GetItem(name);
	ADO_END;
}

/////////////////////////////////////////////////////////

bool TADOField::GetActualSize(long* size)
{
	ADO_START;
	*size = m_pField->GetActualSize();
	ADO_END;
}

bool TADOField::GetDefinedSize(long* size)
{
	ADO_START;
	*size = m_pField->GetDefinedSize();
	ADO_END;
}

bool TADOField::GetName(CString* name)
{
	ADO_START;
	*name = (LPCTSTR)m_pField->GetName();
	ADO_END;
}

bool TADOField::GetType(DataTypeEnum* type)
{
	ADO_START;
	*type = m_pField->GetType();
	ADO_END;
}

bool TADOField::GetAttributes(long* attrib)
{
	ADO_START;
	*attrib = m_pField->GetAttributes();
	ADO_END;
}

bool TADOField::GetProperties(TADOProperties* props)
{
	ADO_START;
	props->m_pProperties = m_pField->GetProperties();
	ADO_END;
}

bool TADOField::GetValue(VARIANT* value)
{
	ADO_START;
	*value = m_pField->GetValue();
	ADO_END;
}

bool TADOField::SetValue(VARIANT value)
{
	ADO_START;
	HRESULT h = m_pField->put_Value(value);
	if (FAILED(h)) {
		bResult = false;
		m_LastError = _T("Failed to set field value");
	}
	ADO_END;
}

/////////////////////////////////////////////////////////

bool TADOFields::GetCount(long* count)
{
	ADO_START;
	*count = m_pFields->GetCount();
	ADO_END;
}

bool TADOFields::GetItem(long index, TADOField* p)
{
	ADO_START;
	p->m_pField = m_pFields->GetItem(index);
	ADO_END;
}

bool TADOFields::GetItem(LPCTSTR name, TADOField* p)
{
	ADO_START;
	p->m_pField = m_pFields->GetItem(name);
	ADO_END;
}

/////////////////////////////////////////////////////////

#ifndef UNDER_CE

TADOConnection::TADOConnection()
{
	m_pCon.CreateInstance(__uuidof(Connection));
}

TADOConnection::~TADOConnection()
{
	if (m_pCon != NULL) {
		if (m_pCon->State == adStateOpen) m_pCon->Close();
		//m_pCon->Release();
	}
}

bool TADOConnection::Open(LPCTSTR connectString, LPCTSTR userID, LPCTSTR password, long options)
{
	ADO_START;
	m_pCon->Open(connectString, userID, password, options);
	ADO_END;
}

bool TADOConnection::Execute(LPCTSTR command, long* numRecsAffected, long options)
{
	ADO_START;
	_variant_t var;
	m_pCon->Execute(command, &var, options);
	if (numRecsAffected) *numRecsAffected = (long)var;
	ADO_END;
}

bool TADOConnection::Close()
{
	ADO_START
	if ((m_pCon != NULL) && (m_pCon->State == adStateOpen)) {
		m_pCon->Close();
	}
	ADO_END
}

bool TADOConnection::GetConnectionString()
{
	return false;
}

bool TADOConnection::SetConnectionString()
{
	return false;
}

bool TADOConnection::GetCommandTimeout()
{
	return false;
}

bool TADOConnection::SetCommandTimeout()
{
	return false;
}

bool TADOConnection::GetConnectTimeout()
{
	return false;
}

bool TADOConnection::SetConnectTimeout()
{
	return false;
}

bool TADOConnection::GetCursorLocation()
{
	return false;
}

bool TADOConnection::SetCursorLocation(CursorLocationEnum loc)
{
	ADO_START
	m_pCon->PutCursorLocation(loc);
	ADO_END
}

bool TADOConnection::GetDefaultDatabase()
{
	return false;
}

bool TADOConnection::SetDefaultDatabase()
{
	return false;
}

bool TADOConnection::GetProvider(CString* provider)
{
	ADO_START;
	*provider = (LPCTSTR)m_pCon->GetProvider();
	ADO_END;
}

bool TADOConnection::SetProvider(CString provider)
{
	ADO_START;
	m_pCon->PutProvider((LPCTSTR)provider);
	ADO_END;
}

bool TADOConnection::GetState(long* state)
{
	ADO_START;
	*state = m_pCon->State;
	ADO_END;
}

bool TADOConnection::BeginTrans(long* result)

{
	ADO_START;
	long rr = m_pCon->BeginTrans();
	if (result != NULL) {
		*result = rr;
	}
	ADO_END;
}

bool TADOConnection::CommitTrans()
{
	ADO_START;
	m_pCon->CommitTrans();
	ADO_END;
}

bool TADOConnection::RollbackTrans()
{
	ADO_START;
	m_pCon->RollbackTrans();
	ADO_END;
}

#endif // UNDER_CE

//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

TADORecordset::TADORecordset()
{
#ifdef UNDER_CE
	HRESULT h = CoCreateInstance(CLSID_ADOCERecordset, NULL, CLSCTX_INPROC_SERVER,
		IID_IADOCERecordset, (void**)&m_pRs);

	if (FAILED(h)) {
		RunTimeError(_T("Failed to create recordset COM interface"));
	}
#else
	m_pRs.CreateInstance(__uuidof(Recordset));
#endif
}

TADORecordset::~TADORecordset()
{
	try {
		if (m_pRs->State != adStateClosed) {
			m_pRs->Close();
		}
		#ifdef UNDER_CE
			if (m_pRs) m_pRs->Release();
		#endif
	}
	catch(...) {
		OutputDebugString("****** Exception in TADORecordset destructor *******\n");
	}
}

bool TADORecordset::Open(LPCTSTR command, LPCTSTR con, long cursorType, long lockType,
						 long options)
{
	ADO_START;
	m_pRs->Open(command, con, static_cast<CursorTypeEnum>(cursorType),
		static_cast<LockTypeEnum>(lockType), options);
	ADO_END;
}

bool TADORecordset::Open(LPCTSTR command, TADOConnection& con, long cursorType,
						 long lockType, long options)
{
	ADO_START;
	m_pRs->Open(command, con.m_pCon.GetInterfacePtr(), static_cast<CursorTypeEnum>(cursorType),
		static_cast<LockTypeEnum>(lockType), options);
	ADO_END;
}

bool TADORecordset::Close()
{
	ADO_START;
	if (m_pRs->State != adStateClosed) {
		m_pRs->Close();
	}
	ADO_END;
}

bool TADORecordset::GetProperties(TADOProperties* props)
{
	ADO_START;
	props->m_pProperties = m_pRs->GetProperties();
	ADO_END;
}

bool TADORecordset::GetFields(TADOFields* fields)
{
	ASSERT(fields != NULL);
	ADO_START;
	fields->m_pFields = m_pRs->Fields;
	ADO_END;
}

bool TADORecordset::AddNew()
{
	ADO_START;
	if (FAILED(m_pRs->AddNew())) {
		bResult = false;
		m_LastError.Empty();
	}
	ADO_END;
}

bool TADORecordset::Delete(AffectEnum affect)
{
	ADO_START;
	if (FAILED(m_pRs->Delete(affect))) {
		bResult = false;
		m_LastError.Empty();
	}
	ADO_END;
}

bool TADORecordset::Find(LPCTSTR criteria, long skipRecs,
						 SearchDirectionEnum srchDir, _variant_t start)
{
	ADO_START;
	if (FAILED(m_pRs->Find(criteria, skipRecs, srchDir, start))) {
		bResult = false;
		m_LastError.Empty();
	}
	ADO_END;
}

bool TADORecordset::GetRows()
{
	m_LastError = _T("Unimplemented function or property");
	return false;
}

bool TADORecordset::GetString(long stringFormat, long numRows, LPCTSTR colDelimeter,
							  LPCTSTR rowDelimeter, LPCTSTR nullExp, CString* result)
{
	ADO_START;
	*result = (LPCTSTR)m_pRs->GetString(static_cast<StringFormatEnum>(stringFormat), numRows,
		colDelimeter, rowDelimeter, nullExp);
	ADO_END;
}

bool TADORecordset::Move()
{
	m_LastError = _T("Unimplemented function or property");
	return false;
}

bool TADORecordset::MoveFirst()
{
	ADO_START;
	if (FAILED(m_pRs->MoveFirst())) {
		bResult = false;
		m_LastError.Empty();
	}
	ADO_END;
}

bool TADORecordset::MoveLast()
{
	ADO_START;
	if (FAILED(m_pRs->MoveLast())) {
		bResult = false;
		m_LastError.Empty();
	}
	ADO_END;
}

bool TADORecordset::MoveNext()
{
	ADO_START;
	if (FAILED(m_pRs->MoveNext())) {
		bResult = false;
		m_LastError.Empty();
	}
	ADO_END;
}

bool TADORecordset::MovePrevious()
{
	ADO_START;
	if (FAILED(m_pRs->MovePrevious())) {
		bResult = false;
		m_LastError.Empty();
	}
	ADO_END;
}

bool TADORecordset::Requery()
{
	m_LastError = _T("Unimplemented function or property");
	return false;
}

bool TADORecordset::Resync()
{
	m_LastError = _T("Unimplemented function or property");
	return false;
}

bool TADORecordset::Save()
{
	m_LastError = _T("Unimplemented function or property");
	return false;
}

bool TADORecordset::Supports()
{
	m_LastError = _T("Unimplemented function or property");
	return false;
}

bool TADORecordset::Update()
{
	ADO_START;
	if (FAILED(m_pRs->Update())) {
		m_LastError.Empty();
		bResult = false;
	}
	ADO_END;
}

bool TADORecordset::CancelUpdate()
{
	ADO_START;
	if (FAILED(m_pRs->CancelUpdate())) {
		m_LastError.Empty();
		bResult = false;
	}
	ADO_END;
}

bool TADORecordset::GetAbsolutePage()
{
	m_LastError = _T("Unimplemented function or property");
	return false;
}

bool TADORecordset::SetAbsolutePage()
{
	m_LastError = _T("Unimplemented function or property");
	return false;
}

bool TADORecordset::GetAbsolutePosition(long* pos)
{
	ADO_START;
	PositionEnum posEnum;
	if (FAILED(m_pRs->get_AbsolutePosition(&posEnum))) {
		bResult = false;
		m_LastError.Empty();
	}
	*pos = static_cast<long>(posEnum);
	ADO_END;
}

bool TADORecordset::SetAbsolutePosition(long pos)
{
	ADO_START;
	if (FAILED(m_pRs->put_AbsolutePosition(static_cast<PositionEnum>(pos)))) {
		bResult = false;
		m_LastError.Empty();
	}
	ADO_END;
}

bool TADORecordset::GetBOF(bool* bBOF)
{
	ADO_START;
	*bBOF = m_pRs->BOF == VARIANT_TRUE;
	ADO_END;
}

bool TADORecordset::GetEOF(bool* bEOF)
{
	ADO_START;
	*bEOF = m_pRs->EndOfFile == VARIANT_TRUE;
	ADO_END;
}

bool TADORecordset::GetCursorLocation()
{
	m_LastError = _T("Unimplemented function or property");
	return false;
}

bool TADORecordset::SetCursorLocation(CursorLocationEnum loc)
{
	ADO_START;
	m_pRs->PutCursorLocation(loc);
	ADO_END;
}

bool TADORecordset::GetCursorType()
{
	m_LastError = _T("Unimplemented function or property");
	return false;
}

bool TADORecordset::SetCursorType()
{
	m_LastError = _T("Unimplemented function or property");
	return false;
}

bool TADORecordset::GetEditMode()
{
	m_LastError = _T("Unimplemented function or property");
	return false;
}

bool TADORecordset::SetEditMode()
{
	m_LastError = _T("Unimplemented function or property");
	return false;
}

bool TADORecordset::GetLockType()
{
	m_LastError = _T("Unimplemented function or property");
	return false;
}

bool TADORecordset::SetLockType()
{
	m_LastError = _T("Unimplemented function or property");
	return false;
}

bool TADORecordset::GetRecordCount(long* size)
{
	ADO_START;
	*size = m_pRs->GetRecordCount();
	ADO_END;
}

bool TADORecordset::GetSort()
{
	m_LastError = _T("Unimplemented function or property");
	return false;
}

bool TADORecordset::SetSort()
{
	m_LastError = _T("Unimplemented function or property");
	return false;
}

bool TADORecordset::GetSource()
{
	m_LastError = _T("Unimplemented function or property");
	return false;
}

bool TADORecordset::SetSource()
{
	m_LastError = _T("Unimplemented function or property");
	return false;
}

bool TADORecordset::GetState()
{
	m_LastError = _T("Unimplemented function or property");
	return false;
}

bool TADORecordset::GetStatus()
{
	m_LastError = _T("Unimplemented function or property");
	return false;
}

//////////////////////////////////////
#endif // ADO_SUPPORT
